package com.ruoyi.web.controller.danger;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.config.ESConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.opio.util.ExampleBase;
import com.ruoyi.system.mapper.HistoryPointDataMapper;
import com.ruoyi.system.entity.HistoryPointData;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/historyPointData")
public class HistoryPointDataController {

    @Autowired
    private RestHighLevelClient client;

    @GetMapping("/getHistoryData")
    public AjaxResult getTimeData(String start,String end,String databaseName) throws IOException {
        if (StrUtil.isEmpty(databaseName)) {
            return AjaxResult.error("未接收到实时数据库位号");
        }
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder must = QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("databaseName", databaseName))
                .must(QueryBuilders.rangeQuery("createTime").gte(DateUtil.parse(start).getTime()).lte(DateUtil.parse(end).getTime()));
        searchSourceBuilder.query(must);
        searchSourceBuilder.sort("createTime");
        searchSourceBuilder.size(1000000);
        SearchRequest searchRequest = new SearchRequest();
        SearchRequest source = searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(source, RequestOptions.DEFAULT);
        List<HistoryPointData> historyPointDataList = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            String sourceAsString = hit.getSourceAsString();
            HistoryPointData historyPointData = JSONUtil.toBean(sourceAsString, HistoryPointData.class);
            historyPointDataList.add(historyPointData);
        }
        return AjaxResult.success(historyPointDataList);
    }

    @Scheduled(cron = "0/60 * * * * ?")
    public void insertData() throws IOException {
        Map<String, Object> map = ExampleBase.toResult();
        if (CollUtil.isNotEmpty(map)) {
            Set<String> set = map.keySet();
            for (String key : set) {
                HistoryPointData historyPointData = new HistoryPointData();
                historyPointData.setDatabaseName(key);
                historyPointData.setDataValue(map.get(key).toString());
                historyPointData.setCreateTime(LocalDateTime.now());
                historyPointData.setUpdateTime(LocalDateTime.now());
                IndexRequest indexRequest = new IndexRequest("point_data");
                indexRequest.timeout(TimeValue.timeValueSeconds(5));
                indexRequest.source(JSONUtil.toJsonStr(historyPointData), XContentType.JSON);
                client.index(indexRequest,RequestOptions.DEFAULT);
            }
        }
    }

    @Scheduled(cron = "00 00 01 * * ?")
    public void deleteData() throws IOException {
        DateTime offset = DateUtil.offset(DateUtil.date(), DateField.YEAR, -1);
        String format = DateUtil.format(offset, "yyyy-MM-dd HH:mm:ss");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder must = QueryBuilders.boolQuery()
                .must(QueryBuilders.rangeQuery("createTime").lte(DateUtil.parse(format).getTime()));
        searchSourceBuilder.query(must);
        searchSourceBuilder.sort("createTime");
        SearchRequest searchRequest = new SearchRequest();
        SearchRequest source = searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(source, RequestOptions.DEFAULT);
        for (SearchHit hit : search.getHits().getHits()) {
            String id = hit.getId();
            client.delete(new DeleteRequest("point_data",id),RequestOptions.DEFAULT);
        }
    }

    @GetMapping("/test")
    public void test(@RequestBody Map<String, Object> map) throws IOException {
        if (CollUtil.isNotEmpty(map)) {
            Set<String> set = map.keySet();
            for (String key : set) {
                HistoryPointData historyPointData = new HistoryPointData();
                historyPointData.setDatabaseName(key);
                historyPointData.setDataValue(map.get(key).toString());
                historyPointData.setCreateTime(LocalDateTime.now());
                historyPointData.setUpdateTime(LocalDateTime.now());
                IndexRequest indexRequest = new IndexRequest("point_data");
                indexRequest.source(JSONUtil.toJsonStr(historyPointData), XContentType.JSON);
                client.index(indexRequest,RequestOptions.DEFAULT);
            }
        }
    }

    @GetMapping("/getAll")
    public AjaxResult getAll() throws IOException {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        MatchAllQueryBuilder must = QueryBuilders.matchAllQuery();
        searchSourceBuilder.query(must);
        searchSourceBuilder.size(1000000);
        SearchRequest searchRequest = new SearchRequest();
        SearchRequest source = searchRequest.source(searchSourceBuilder);
        SearchResponse search = client.search(source, RequestOptions.DEFAULT);
        List<HistoryPointData> historyPointDataList = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            String sourceAsString = hit.getSourceAsString();
            HistoryPointData historyPointData = JSONUtil.toBean(sourceAsString, HistoryPointData.class);
            historyPointDataList.add(historyPointData);
        }
        return AjaxResult.success(historyPointDataList);
    }

}
